package com.tz.farmer.service.impl;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smartPark.msframe.result.ResultEx;
import com.tz.farmer.config.RedisConfig;
import com.tz.farmer.enums.ErrorCodeEnum;
import com.tz.farmer.mapper.FarmerUserInfoMapper;
import com.tz.farmer.model.FarmerUserInfo;
import com.tz.farmer.service.UserLoginService;
import com.tz.farmer.so.FarmerUserInfoSo;
import com.tz.farmer.util.AES;
import com.tz.farmer.util.ResultExM;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import redis.clients.jedis.Jedis;
import javax.annotation.Resource;
import java.util.*;

@Service
public class UserLoginServiceImpl extends ServiceImpl<FarmerUserInfoMapper , FarmerUserInfo> implements UserLoginService {

   @Resource
    FarmerUserInfoMapper farmerUserInfoMapper;


    @Override
    public ResultEx login(FarmerUserInfoSo so) {
        try {
            so.setUserAccount(AES.Decrypt(so.getUserAccount(), "a2k45j7i901q34m6"));
            so.setPassword(AES.Decrypt(so.getPassword(), "a2k45j7i901q34m6"));
            so.setUserAccount("admin");
            so.setPassword("tzsj@13579!!!");
        }catch (Exception e){
            return ResultEx.builder().makeResult(500, "用户名密码不正确", "用户名密码不正确");
        }
        Jedis jedis = null;
        try {
            jedis = RedisConfig.getJedis();
            if (jedis != null) {
                String loginCount=jedis.get(so.getUserAccount());
                if(StringUtils.isBlank(loginCount)){
                    jedis.set(so.getUserAccount(),"1" );
                }else{
                    if(Integer.valueOf(loginCount)>=5){
                        return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_ACCOUNT_STATUS_FREEZE_ERROR);
                    }else {
                        jedis.set(so.getUserAccount(), (Integer.valueOf(loginCount) + 1)+"");
                        jedis.expire(so.getUserAccount(),300);

                    }
                }

            } else {
                return null;
            }
        } catch (Exception e) {
            return null;
        } finally {
            if (jedis != null) {
                RedisConfig.returnJedis(jedis);
            }
        }
        int have = this.count(new QueryWrapper<FarmerUserInfo>()
                .eq(StringUtils.isNotEmpty(so.getUserAccount()), "user_account", so.getUserAccount()));
        if (have <= 0) {
            return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_NO_USERNAME_ERROR);
        }

            FarmerUserInfo farmerUserInfo = farmerUserInfoMapper.selectOne(
                    new QueryWrapper<FarmerUserInfo>()
                            .eq("user_account", so.getUserAccount())
                            .eq("password", DigestUtils.md5DigestAsHex(so.getPassword().getBytes()))
            );

            if(ObjectUtils.isNotEmpty(farmerUserInfo) && farmerUserInfo.getIsUse()  != 1){
                Map<String , Object> map =  new HashMap<>();
                map.put("userAccount",farmerUserInfo.getUserAccount());
                map.put("token", generateUserToken(farmerUserInfo.getId(),farmerUserInfo.getName(),farmerUserInfo.getUserPhone(),farmerUserInfo.getUserAccount()));
                //查询登陆人权限列表
                List<String> funs=farmerUserInfoMapper.selectFunByUser(farmerUserInfo.getId());
                map.put("funs",funs);
                return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_SUCCEED,map);
            }
        return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_NO_USERNAME_ERROR);

    }


    private String generateUserToken(Integer userId, String userName,  String phone ,String userAccount) {
        UUID uuid = UUID.randomUUID();
        String token = uuid.toString();
        Jedis jedis = null;
        try {
            jedis = RedisConfig.getJedis();
            if (jedis != null) {
                jedis.set(token, userId + "_" + userName + "_" + phone+"_"+userAccount);
                //设置过期时间 一小时
                jedis.expire(token,7200);
            } else {
                return null;
            }
        } catch (Exception e) {
            return null;
        } finally {
            if (jedis != null) {
                RedisConfig.returnJedis(jedis);
            }
        }
        return token;
    }

    public static String convertMD5(String inStr){

        char[] a = inStr.toCharArray();
        for (int i = 0; i < a.length; i++){
            a[i] = (char) (a[i] ^ 't');
        }
        String s = new String(a);
        return s;

    }

    public static void main(String[] args) {
        try {
            String inStr = "6l1AKPlAx/XK8PmAW8SQxg==";
            System.out.println(AES.Decrypt(inStr, "a2k45j7i901q34m6"));
        }catch (Exception e){
        }
    }
}
